package com.atguigu.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


@Configuration
public class MyRabbitConfig {
    /**
     * 使用JSON序列化机制,进行消息转换
     * @return
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    //监听消息,让交换机和队列,绑定初始化
//    @RabbitListener(queues = "stock.release.stock.queue")
//    public void handle(Message message){
//
//    }
    //交换机
    @Bean
    public Exchange stockEventExchange(){
        //String name, boolean durable, boolean autoDelete, Map<String, Object> arguments
        //创建交换机
        return new TopicExchange("stock-event-exchange",true,false);
    }
    //队列
    @Bean
    public Queue stockReleaseStockQueue(){
        //创建返回普通队列
        return new Queue("stock.release.stock.queue",true,false,false);
    }
    //延迟队列
    @Bean
    public Queue stockDelayQueue(){
        //Map
        Map<String,Object> args = new HashMap<>();
        //设置交换机
        args.put("x-dead-letter-exchange","stock-event-exchange");
        //设置路由键
        args.put("x-dead-letter-routing-key","stock.release");
        //设置过期时间
        args.put("x-message-ttl",120000);
        //创建队列
        return new Queue("stock.delay.queue",true,false,false,args);

    }
    //绑定关系
    @Bean
    public Binding stockReleaseBinding(){
        //String destination, DestinationType destinationType, String exchange, String routingKey,
        //			Map<String, Object> arguments
        //创建返回绑定关系
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",
                null);
    }
    //绑定关系
    @Bean
    public Binding stockLockedBinding(){
        //String destination, DestinationType destinationType, String exchange, String routingKey,
        //			Map<String, Object> arguments
        //创建返回绑定关系
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",
                null);
    }

}
